package com.tz.farmer.controller;

import cn.hutool.crypto.SecureUtil;
import com.tz.farmer.config.SsoProperties;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 单点登录接口
 * @author fengy
 * @since 2023/3/26 026
 */
@Controller
@RequestMapping("/sso")
@Api(tags = "单点登录")
public class SsoController {

    @Autowired
    private SsoProperties ssoProperties;

    @RequestMapping
    public String ssoLogin(String token) {
        if (StringUtils.isEmpty(token)) {
            return ssoProperties.getFaildPath();
        }
        try {
            String res = SecureUtil.des(ssoProperties.getSecKey().getBytes(StandardCharsets.UTF_8)).decryptStr(token);
            if (StringUtils.isEmpty(res)) {
                return ssoProperties.getFaildPath();
            }
            String[] ress = res.split(",");
            if (ress.length == 2) {
                String user = ress[0];
                String ts = ress[1];
                Date date = new Date(Long.valueOf(ts));
                // TOKEN过期
                if (date.before(new Date())) {
                    return ssoProperties.getFaildPath();
                }
                // 用户
//                String sysUser = ssoProperties.getUserMap().get(user);

                return ssoProperties.getSuccessPath();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssoProperties.getFaildPath();
    }
}
